package com.eliza.net.activity

import android.os.Build
import android.os.Bundle
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.eliza.library.tools.InfoTools
import com.eliza.net.R

class WebViewActivity : AppCompatActivity() {
    lateinit var wv: WebView
    lateinit var tv: TextView
    private var exitTime: Long = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_webview)

        wv = findViewById<WebView>(R.id.webView_wv)
        tv = findViewById<TextView>(R.id.webView_tv)

        wvConfig()
    }

    fun wvConfig() {

        wv.webChromeClient = object : WebChromeClient() {
            //这里设置获取到的网站title
            override fun onReceivedTitle(view: WebView, title: String) {
                super.onReceivedTitle(view, title)
                tv.text = title
            }
        }

        wv.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                InfoTools.ToastTools(this@WebViewActivity, "webViewClient::$view")
                view?.let {
                    request?.let {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            view.loadUrl(request.url.toString());
                        } else {
                            view.loadUrl(request.toString());
                        }
                    }
                }
                return true
            }

        }

        wv.settings.also {
            it.useWideViewPort = true;//设定支持viewport
            it.loadWithOverviewMode = true;   //自适应屏幕
            it.builtInZoomControls = true;
            it.displayZoomControls = false;
            it.setSupportZoom(true);//设定支持缩放
            it.javaScriptEnabled = true;  //设置WebView属性,运行执行js脚本
        }
        wv.loadUrl("https://developer.android.google.cn/");          //调用loadUrl方法为WebView加入链接

    }

    /**
     *  我们需要重写回退按钮的时间,当用户点击回退按钮：
     * 1.webView.canGoBack()判断网页是否能后退,可以则goback()
     * 2.如果不可以连续点击两次退出App,否则弹出提示Toast
     *   */
    override fun onBackPressed() {
        if (wv.canGoBack()) {
            wv.goBack();
        } else {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                InfoTools.ToastTools(this, "再按一次退出程序")
                exitTime = System.currentTimeMillis();
            } else {
                super.onBackPressed();
            }
        }
    }
}